package cc.chenwenxi.sdk.demo;

import java.util.concurrent.Callable;

import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalInput;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.PinPullResistance;
import com.pi4j.io.gpio.PinState;
import com.pi4j.io.gpio.RaspiPin;
import com.pi4j.io.gpio.trigger.GpioCallbackTrigger;
import com.pi4j.io.gpio.trigger.GpioPulseStateTrigger;
import com.pi4j.io.gpio.trigger.GpioSetStateTrigger;
import com.pi4j.io.gpio.trigger.GpioSyncStateTrigger;

public class TriggerGpio {
	public static void main(String[] args) throws InterruptedException {

		System.out.println("< -  Pi4J  - > GPIO触发器示例...已启动。");

		// 创建gpio控制器
		final GpioController gpio = GpioFactory.getInstance();

		// 将gpio引脚＃02设置为输入引脚,并使能其内部下拉电阻
		final GpioPinDigitalInput myButton = gpio.provisionDigitalInputPin(RaspiPin.GPIO_02, PinPullResistance.PULL_DOWN);

		System.out.println("......完成GPIO＃02电路并看到触发器生效。");

		// 将gpio引脚＃04,＃05,＃06设置为输出引脚,并确保它们在启动时均为低电平
		GpioPinDigitalOutput myLed[] = { gpio.provisionDigitalOutputPin(RaspiPin.GPIO_04, "LED＃1", PinState.LOW),
				gpio.provisionDigitalOutputPin(RaspiPin.GPIO_05, "LED＃2", PinState.LOW),
				gpio.provisionDigitalOutputPin(RaspiPin.GPIO_06, "LED＃3", PinState.LOW) };

		// 在输入引脚上创建一个gpio控制触发器; 当输入变为高电平时,也将gpio引脚＃04设置为HIGH
		myButton.addTrigger(new GpioSetStateTrigger(PinState.HIGH, myLed[0], PinState.HIGH));

		// 在输入引脚上创建一个gpio控制触发器; 当输入变为低电平时,也将gpio引脚＃04设置为LOW
		myButton.addTrigger(new GpioSetStateTrigger(PinState.LOW, myLed[0], PinState.LOW));

		// 在输入引脚上创建一个gpio同步触发器; 当输入改变时,也将gpio引脚＃05设置为相同的状态
		myButton.addTrigger(new GpioSyncStateTrigger(myLed[1]));

		// 在输入引脚上创建一个gpio脉冲触发器; 当输入变为高电平时,也将gpio引脚＃06脉冲为高电平状态1秒
		myButton.addTrigger(new GpioPulseStateTrigger(PinState.HIGH, myLed[2], 1000));

		// 在gpio pin＃4上创建一个gpio回调触发器; 当＃4改变状态时,执行回调
		// 在用户定义的'Callable'类实例上调用
		myButton.addTrigger(new GpioCallbackTrigger(new Callable<Void>() {
			public Void call() throws Exception {
				System.out.println(" - > GPIO TRIGGER CALLBACK RECEIVED");
				return null;
			}
		}));

		// 让程序保持运行直到用户中止(CTRL-C)
		while (true) {
			Thread.sleep(500);
		}

		// 通过关闭GPIO控制器来停止所有GPIO活动/线程
		// (此方法将强制关闭所有GPIO监视线程和计划任务)
		// gpio.shutdown(); <---如果要终止Pi4J GPIO控制器,请执行此方法调用
	}
}
